package com.eflow.model.flowable.model;

import cn.hutool.core.collection.CollectionUtil;
import com.eflow.model.domain.EflowUser;
import com.eflow.model.e.BpmConst;
import com.eflow.model.e.SelectUserTypeEnum;
import com.eflow.model.flowable.converter.UserTaskConverter;
import com.eflow.model.flowable.utils.JSONUtil;
import com.eflow.model.service.IEflowUserService;
import com.eflow.model.utils.SpringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.ExtensionAttribute;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.engine.repository.ProcessDefinition;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hui se
 * @description 拓展节点元素
 * @create 2021-02-24 17:19
 **/
@Data
@Slf4j
public class UserTaskExtendElement  implements BpmConst {
    /**
     * 审批用户类型
     */
    private Integer setType;

    /**
     * 指派的节点
     */
    private String pointNode;

    /**
     * 默认的顶级用户
     */
    private boolean defaultTopUser;

    /**
     * 按钮列表
     */
    private List<ButtonElement> buttonList;
    /**
     * 备选用户列表
     */
    private List<UserElement> userList;
    /**
     * 可退回节点
     */
    private List<NodeElement> rejectNodes;

    public List<EflowUser> parseUserList(String loginUser, ProcessDefinition processDefinition, String processInstanceId, String activityId, Map<String,Object> var){
        List<EflowUser> list = new ArrayList<>();
      if(SelectUserTypeEnum.POINT.getCode()== Optional.ofNullable(setType).orElse(Integer.MIN_VALUE).intValue()){
          IEflowUserService userService = SpringUtils.getBean(IEflowUserService.class);
          return   userService.selectUserByUserIds( (List)var.get(pointNode+"_"+VAR_TASK_USER_LIST));

      }else {
          if(userList!=null){
              for (UserElement userElement : userList) {
                  list.addAll(UserTaskConverter.parseUserList(userElement,loginUser, processDefinition,processInstanceId,activityId,var));
              }
          }
          //去重
          list = list.stream().distinct().sorted(Comparator.comparing(EflowUser::getSort)).collect(Collectors.toList());
      }
      if(list.isEmpty()&&defaultTopUser){
          IEflowUserService userService = SpringUtils.getBean(IEflowUserService.class);
          list =  userService.selectUserDeptPostUser(loginUser,TOP_POST);

      }

        return  list;
    }

    public List<ButtonElement> getButtonList() {
        return CollectionUtil.emptyIfNull(buttonList);
    }

    public static UserTaskExtendElement parse(BaseElement element){
        if(element.getExtensionElements().containsKey(EXTENDED)){
            List<ExtensionElement> extensionElements = element.getExtensionElements().get(EXTENDED);
            ExtensionElement extensionElement = extensionElements.get(0);
            Map<String, List<ExtensionAttribute>> attributes = extensionElement.getAttributes();
            String elementText = "";
            if(attributes.containsKey(XML_BODY)){
                ExtensionAttribute body = attributes.get(XML_BODY).get(0);
                elementText =body.getValue();
            }
            //转换JSON为对象
            try {
                return  JSONUtil.objectMapper().readValue(elementText,UserTaskExtendElement.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }else {
            throw new RuntimeException("节点没有拓展属性，无法继续");
        }
    }
}
